package com.example.labtest.webapi;


import com.example.labtest.domain.Admin;
import com.example.labtest.domain.Student;
import com.example.labtest.domain.Student_info;
import com.example.labtest.service.AdminService;
import com.example.labtest.service.StudentInfoService;
import com.example.labtest.service.StudentService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.util.List;

import static java.awt.SystemColor.window;

@RestController
@RequestMapping("webapi/login")
public class LoginRestController {
    //!!千万注意，一个@Autowire注解只能注入一个service

    //注入一个studentServer这样就可以调用student
    @Autowired
    AdminService adminService;
    @Autowired
    StudentService studentService;
    @Autowired
    StudentInfoService studentInfoService;
    //url：webapi/login/user
    @GetMapping("/user")

    //httprequest请求会让我们获得session
    public int user(Model model, HttpServletRequest httpRequest, @RequestParam(value="username")String username, String password, String UserID) {
        model.addAttribute("username",username);

        if (UserID.equals("1"))
        {
            //判断用户名和密码是否存在
            List<Student_info> students = studentInfoService.findByNameAndPsw(username, password);

        if (students.size() > 0) {

            //如果存在，则写入session
            HttpSession session = httpRequest.getSession();
            //向获取到的session里面放两个属性
            session.setAttribute("userid", students.get(0).getId());
            session.setAttribute("userpsw",students.get(0).getPsw());
            session.setAttribute("user", students.get(0));
            return 1;//成功
        }
        else {
            //如果不存在，则返回出错
            return -1;
        }
        }
        else if(UserID.equals("2"))
        {
            //判断用户名和密码是否存在
            List <Admin> admins=adminService.findByAdmnameAndAdmpsw(username,password);
            if (admins.size() > 0) {
                //如果存在，则写入session
                HttpSession session = httpRequest.getSession();
                //向获取到的session里面放两个属性
                session.setAttribute("userid", admins.get(0).getAdmid());
                session.setAttribute("user", admins.get(0));
                return 2;//成功
            }
            else {
                //如果不存在，则返回出错
                return -1;
            }
        }
       else if(UserID.equals("3"))
        {
            return 3;
        }
        else{
            return -1;
        }
    }


}



